package com.jlcloud.core.xss;

import lombok.experimental.UtilityClass;
import org.springframework.util.ObjectUtils;

import java.util.Objects;

/**
 * 利用 ThreadLocal 缓存线程间的数据
 *
 * @author By: JlCloud <br>
 * @Package: com.jlcloud <br>
 * @CreateTime: 2024-12-03 21:45 <br>
 * @Copyright: 2021 www.jilianjituan.com Inc. All rights reserved. <br>
 * @Caution 注意：本内容仅限于冀联人力集团内部传阅，禁止外泄以及用于其他的商业目的 <br>
 */
@UtilityClass
public class XssHolder {
	private static final ThreadLocal<XssIgnoreRules> TL = new ThreadLocal<>();

	/**
	 * 是否开启
	 *
	 * @return boolean
	 */
	public static boolean isEnabled() {
		return Objects.isNull(TL.get());
	}

	/**
	 * 判断是否被忽略
	 *
	 * @return XssCleanIgnore
	 */
	public static boolean isIgnore(String name) {
		XssIgnoreRules ignoreRules = TL.get();
		if (ignoreRules == null) {
			return false;
		}
		String[] ignoreNames = ignoreRules.getNames();
		// 1. 如果没有设置忽略的字段
		if (ignoreNames.length == 0) {
			return true;
		}
		// 2. 指定忽略的属性
		return ObjectUtils.containsElement(ignoreNames, name);
	}

	/**
	 * 标记为开启
	 */
	public static void setIgnore(XssIgnoreRules ignoreRules) {
		TL.set(ignoreRules);
	}

	/**
	 * 关闭 xss 清理
	 */
	public static void remove() {
		TL.remove();
	}

}
